package com.example.websocket.client;

import org.springframework.web.socket.*;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.springframework.web.socket.client.WebSocketClient;
import java.net.URI;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class MyWebSocketClient {
    private WebSocketSession webSocketSession;
    private WebSocketHandler webSocketHandler = new TextWebSocketHandler() {
        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            System.out.println("Connected to WebSocket");
        }

        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            System.out.println("Received message: " + message.getPayload());
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
            System.out.println("Connection closed");
        }
    };

    public void connect(String url) throws Exception {
        StandardWebSocketClient client = new StandardWebSocketClient();
        Future<WebSocketSession> session = client.doHandshake(webSocketHandler, url); // 握手并创建会话
        webSocketSession = session.get(2, TimeUnit.SECONDS); // 获取会话，设置超时时间10秒
    }

    public void sendMessage(WebSocketMessage<?> message) throws Exception {
        webSocketSession.sendMessage(message); // 发送消息到服务器
        Thread.sleep(10000);
        webSocketSession.close(); // 关闭会话
    }
}